from django.http import HttpResponse, JsonResponse, HttpRequest
from django.shortcuts import render, get_object_or_404, redirect
from django.urls.base import reverse_lazy,reverse
from django.contrib.auth.decorators import login_required
import uuid

from datetime import datetime
# 请求装饰器
from django.views.decorators.http import require_http_methods
import os

from .models import Blog,Category,BlogComment

def index(request):
    blogs = Blog.objects.all()
    return render(request, "blog/index.html",context={"blogs":blogs})


def blog_details(request, blog_id):
    try:
        blog_model = Blog.objects.get(id=blog_id)
        blog_comments = BlogComment.objects.filter(blog_id=blog_model)
    except Exception as e:
        blog_model = None
    return render(request, 'blog/blog_detail.html',
                  context={'blog_model':blog_model,'commentCount':blog_comments.count(),'blog_comments':blog_comments})


def gratefile(request):
    cover = request.FILES.get("cover")
    if not cover:
        return ""
    file_dirs = f'static/covers'
    filename = f'static/covers/{str(uuid.uuid4())}.jpg'
    if not os.path.exists(file_dirs):
        os.makedirs(file_dirs)
    with open(filename, 'wb') as f:
        f.write(cover.read())
    return filename


# login_required这个装饰器代表 每次请求需要查看是否已经登陆，若没有登录则会跳转到指定的login_url
@login_required(login_url='/login')
def publish_blog(request):
    if request.method == 'POST':
        filename = gratefile(request)
        # cover = request.FILES['cover']
        # file_dirs = f'static/covers'
        # filename = f'static/covers/{str(uuid.uuid4())}.jpg'
        # if not os.path.exists(file_dirs):
        #     os.makedirs(file_dirs)
        # with open(filename, 'wb') as f:
        #     f.write(cover.read())
        content = request.POST['content']
        classify = request.POST['classify']
        title = request.POST['title']
        datetime_object = datetime.strptime(request.POST['date_time'], '%Y-%m-%dT%H:%M')
        date_time = datetime_object.strftime('%Y-%m-%d %H:%M:%S')
        Blog.objects.create(content=content, classify=classify,title=title,cover=filename, date_time=date_time)
        return render(request, 'blog/publish_blog.html', {'data': True, 'code': 200, 'msg': "发布成功!"})
    else:
        categories = Category.objects.all()
        return render(request, 'blog/publish_blog.html',context={'categories':categories})

def publish_blog_comment(request):
    content = request.POST['content']
    blog_id = request.POST['blog_id']
    blog = Blog.objects.get(id=blog_id)
    BlogComment.objects.create(blog_id=blog, content=content)
    return JsonResponse({'code': 200, 'msg': '评论成功！'})

def process_img(obj:Blog):
    if obj.cover:
        obj.cover = 'http://localhost:8000/' + obj.cover
    return obj


# 博客列表
@login_required(login_url="/login")
def blog_list(request):
    blogs = list(map(process_img,  Blog.objects.all()))
    return render(request, 'managment/blog_list.html', {'blogs': blogs})

from .forms import BlogForm
# 博客详情
@login_required(login_url='/login')
def blog_detail(request, id):
    blog = get_object_or_404(Blog, id=id)
    return render(request, 'managment/blog_detail.html', {'blog': blog})

# 创建博客
@login_required(login_url='/login')
def blog_create(request):
    if request.method == 'POST':
        blog_form = BlogForm(request.POST)
        if blog_form.is_valid():
            title = request.POST['title']
            classify = request.POST['classify']
            content = request.POST['content']
            cover = request.POST['cover']
            Blog.objects.create(title=title, classify=classify, content=content, cover=cover)
            return redirect('blog:blog_list')
    return render(request, 'managment/blog_form.html')

# 更新博客
@login_required(login_url='/login')
def blog_update(request, id):
    blog = get_object_or_404(Blog, id=id)
    if request.method == 'POST':
        blog.title = request.POST['title']
        blog.classify = request.POST['classify']
        blog.content = request.POST['content']
        blog.cover = gratefile(request)
        blog.save()
        return redirect('blog:blog_list')
    return render(request, 'managment/blog_form.html', {'blog': blog})

# 删除博客
@login_required(login_url='/login')
def blog_delete(request, id):
    blog = get_object_or_404(Blog, id=id)
    blog.delete()
    return redirect('blog:blog_list')